package com.yz.jdd.module.cashier.scanpay;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.trello.rxlifecycle.ActivityEvent;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.IntentHandler;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PayConfig;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.Tools;
import com.yz.jdd.module.cashier.result.CloseOrderActivity;
import com.yz.jdd.module.cashier.result.PayFailureActivity;
import com.yz.jdd.module.cashier.result.PaySuccessActivity;
import com.yz.jdd.module.cashier.scanpay.exception.ExceptionModelImpl;
import com.yz.jdd.module.settings.model.PayQrCode;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_Pay;
import com.yz.jdd.network.request.Request_PayStatus;
import com.yz.jdd.network.response.Response_Pay;
import com.yz.jdd.scan.encoding.EncodingUtils;
import com.yz.jdd.widget.PublicDialog;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 付款码页面 2020-01-18
 */

public class PaymentCodeActivity extends BaseActivity implements View.OnClickListener {
    private Activity context;
    private ImageView back_nav;
    private TextView title_nav;
    private TextView right_nav;
    private TextView tv_qr_title;
    private TextView tv_qr_money;
    private ImageView iv_qr;
    private ImageView iv_ali;
    private ImageView iv_wechat;
    private ImageView iv_yunshanfu;
    private Request_Pay request_pay;
    private LinearLayout ll_bottom_image;//底部图标布局
    private LinearLayout ll_pay_ing;//支付中布局
    private ImageView iv_pay_type;//支付方式图标
    private TextView tv_pay_type_desc;//支付方式描述
    private TextView tv_pay_status_desc;//支付状态描述
    private String clientOrderId = "";
    private Subscription periodSubscribtion;
    private Subscription statusSubscribtion;
    private Observable observable;
    private boolean getStatus;//是否得到状态
    private String[] payTypes;//支付方式
    private List<Subscription> subscriptionList;//记录订单状态请求集合
    private TextView tv_desc_paytype;//支付方式底部描述
    private RelativeLayout header_header;
    private ImageView shadow_img;// 阴影
    private ImageView refresh_img;// 阴影转圈
    private TextView tv_qr_tos;
    private FrameLayout fl_qr;


    public PaymentCodeActivity() {
        context = PaymentCodeActivity.this;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isScan = false;
        context = this;
        setContentView(R.layout.activity_paymentcode);
        request_pay = (Request_Pay) getIntent().getSerializableExtra(PayConfig.INTENT_ORDER_FROM);
        initView();
        observable = Observable.interval(0, 3, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread());
        getStatus = false;
        subscriptionList = new ArrayList<>();
        String cash_paytypes = PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREF_CASH_PAYTYPES, "");
        if (!TextUtils.isEmpty(cash_paytypes)) {
            payTypes = cash_paytypes.split("#");
            if (payTypes != null && payTypes.length > 0) {
                String desc = "请顾客使用";
                for (int i = 0; i < payTypes.length; i++) {
                    if ("2".equals(payTypes[i])) {
                        iv_ali.setVisibility(View.VISIBLE);
                        if (i == payTypes.length - 1) {
                            desc = desc + " 支付宝";
                        } else {
                            desc = desc + " 支付宝、";
                        }
                        continue;
                    }
                    if ("5".equals(payTypes[i])) {
                        iv_wechat.setVisibility(View.VISIBLE);
                        if (i == payTypes.length - 1) {
                            desc = desc + " 微信";
                        } else {
                            desc = desc + " 微信、";
                        }
                        continue;
                    }
                    if ("7".equals(payTypes[i])) {
                        iv_yunshanfu.setVisibility(View.VISIBLE);
                        if (i == payTypes.length - 1) {
                            desc = desc + " 云闪付";
                        } else {
                            desc = desc + " 云闪付、";
                        }
                        continue;
                    }
                }
                tv_desc_paytype.setText(desc + "扫描以上二维码完成支付");
            }
        }
        if (request_pay != null) {
            getQrPayUrl();
        }
        registerRxbusEvent();
    }

    /**
     * 获取支付二维码
     */
    private void getQrPayUrl() {
        showLoading("加载中,请稍候...");
        String shopId = PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREF_CASH_SHOPID, "");
        clientOrderId = PayConfig.createClientOrderId(context);
        Log.e("lkf","----- shopId="+shopId);

        if (!TextUtils.isEmpty(shopId)) {
            request_pay.setShopId(shopId);
            request_pay.setClientOrderId(clientOrderId);
            ExceptionModelImpl exceptionModel = new ExceptionModelImpl(context);
            NetWorkRequset.doQrPay(exceptionModel.getRequestPayParam(request_pay), new MySubscriber() {
                @Override
                public void onSuccess(Response_Base response_baseModel) {
                    dismissLoading();
                    if (response_baseModel.getCode().equals("1")) {
                        PayQrCode payQrCode = (PayQrCode) response_baseModel.getResultObject();
                        if (payQrCode != null) {
                            Observable.just(payQrCode.getPayQrcodeUrl())
                                    .map(new Func1<String, Bitmap>() {
                                        @Override
                                        public Bitmap call(String s) {
                                            return EncodingUtils.createQRCode(s, Tools.dip2px(context, 180), Tools.dip2px(context, 180), null);
                                        }
                                    }).subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Action1<Bitmap>() {
                                        @Override
                                        public void call(Bitmap bitmap) {
                                            if (bitmap != null) {
                                                iv_qr.setImageBitmap(bitmap);
                                                intervalStatus();
                                                failureTime(5 * 60 * 1000);
                                            }
                                        }
                                    });
                        }
                    }
                }

                @Override
                public void onNeedLogin(String msg) {
                    dismissLoading();
                }

                @Override
                public void onFail(Response_Base response_baseModel) {
                    dismissLoading();
                    if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                        Toast.makeText(PaymentCodeActivity.this, response_baseModel.getMsg(), Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    }


    /**
     * 遍历订单状态
     */
    private void intervalStatus() {
        unsubscribePeriod();
        periodSubscribtion = observable.subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                getPaymentStatus();
            }
        });
    }

    /**
     * 查询订单状态
     * tips:轮询支付订单结果
     */
    private void getPaymentStatus() {
        final Request_PayStatus request_payStatus = new Request_PayStatus();
        request_payStatus.setClientOrderId(clientOrderId);
//        request_payStatus.setOrderId(orderId); // 不传
//        unsubscribeStatus();
        if (!getStatus) {
            statusSubscribtion = NetWorkRequset.getPayStatus(request_payStatus, new ApiCallback() {
                @Override
                public void onSuccess(Response_Base response) {
                    Response_Pay response_pay = (Response_Pay) response.getResultObject();
                    if (PayConfig.ORDER_STATUS_SUCCESS.equals(response_pay.getPayStatus())) {
                        getStatus = true;
//                            iScanpayView.dismissCountDownLoading();
                        //发消息,刷新首页/列表数据
                        RxBus.getInstance().send(Events.EVENT_VOICE_BROADCAT, "scanpay");

                        LogUtils.Log("shibin", "----支付成功#" + response_pay.getOrderId());
                        unsubscribePeriod();
                        unsubscribeStatus();
                        Intent intent = new Intent(context, PaySuccessActivity.class);
                        Bundle resultBundle = new Bundle();
                        request_pay.setReceiptAmount(response_pay.getReceiptAmount());
                        request_pay.setDiscountAmount(response_pay.getDiscountAmount());
                        request_pay.setTotalAmount(response_pay.getTotalAmount());
                        request_pay.setPayType(response_pay.getPayType());
                        request_pay.setOrderId(response_pay.getOrderId());
//                            args.setOrderType(dealType);
//                        args.setGoodsAmount(response_pay.getGoodsAmount());
                        request_pay.setGooodsAmount(response_pay.getGooodsAmount());
                        //营销新增
                        request_pay.setDeductionAmount(response_pay.getDeductionAmount());
                        request_pay.setReceiveAmountFromPayGate(response_pay.getReceiveAmountFromPayGate());

                        resultBundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
                        //  resultBundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean()); // 传递支付监控数据
                        intent.putExtras(resultBundle);
                        context.startActivity(intent);
                        finish();
                    }

                    if (PayConfig.ORDER_STATUS_FAILUER.equals(response_pay.getPayStatus())) {
                        getStatus = true;
//                            iScanpayView.dismissCountDownLoading();
                        unsubscribePeriod();
                        unsubscribeStatus();
                        Intent intent = new Intent(context, PayFailureActivity.class);
                        Bundle bundle = new Bundle();
                        request_pay.setCode(response.getCode());
//                            args.setOrderType(dealType);
                        request_pay.setPayResultMessage(response.getMsg() != null ? response.getMsg() : "");
                        bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
                        //  bundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean());  // 传递支付监控数据
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                        finish();
                    }
                }

                @Override
                public void onNeedLogin(String msg) {
                    unsubscribePeriod();
                    unsubscribeStatus();
                    IntentHandler.startLoginActivity(context);
                }

                @Override
                public void onFail(Response_Base response_baseModel) {
                    if (response_baseModel != null && "2017".equals(response_baseModel.getCode())) {
                        getStatus = true;
//                        iScanpayView.dismissCountDownLoading();
                        unsubscribePeriod();
                        unsubscribeStatus();
                        Intent intent = new Intent(context, PayFailureActivity.class);
                        Bundle bundle = new Bundle();
                        request_pay.setCode(response_baseModel.getCode());
//                        args.setOrderType(dealType);
                        request_pay.setPayResultMessage(response_baseModel.getMsg() != null ? response_baseModel.getMsg() : "");
                        bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
                        // bundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean()); // 传递支付监控数据
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                        finish();
                    }
                }
            });
            subscriptionList.add(statusSubscribtion);
        }
    }

    public void unsubscribeStatus() {
        if (subscriptionList != null && subscriptionList.size() > 0) {
            for (Subscription subscription : subscriptionList) {
                if (subscription != null) {
                    subscription.unsubscribe();
                    subscription = null;
                }
            }
            subscriptionList.clear();
        }
        LogUtils.Log("lkf", " ------ unsubscribeStatus");

    }


    private void unsubscribePeriod() {
        if (periodSubscribtion != null) {
            periodSubscribtion.unsubscribe();
            periodSubscribtion = null;
        }
        LogUtils.Log("lkf", " ------ unsubscribePeriod");
    }


    Handler handler;
    Runnable runnable;

    /**
     * 设置失效时间
     *
     * @param time
     */
    public void failureTime(int time) {
        if (refresh_img != null) {
            refresh_img.setVisibility(View.GONE);
            shadow_img.setVisibility(View.GONE);

        }
        LogUtils.i("失效时间 ---" + time);
        if (handler != null) {
            handler.removeCallbacks(runnable);
        } else {
            handler = new Handler();
        }
        runnable = new Runnable() {
            @Override
            public void run() {
                getStatus = true;
                unsubscribePeriod();
                unsubscribeStatus();

                if (right_nav.getVisibility() == View.GONE) {
                    Intent intent = new Intent(PaymentCodeActivity.this, CloseOrderActivity.class);
                    intent.putExtra("request_pay", request_pay);
                    // intent.putExtra(PayConfig.INTENT_PAY_DATA, scanpayPresenter.getPayDataBean()); // 传递支付监控数据
                    startActivity(intent);
                    finish();
                    return;
                }
                // 显示刷新与阴影
                LogUtils.i("失付款码生成失败阴影 ");
                if (refresh_img != null) {
                    ll_pay_ing.setVisibility(View.GONE);
                    fl_qr.setVisibility(View.VISIBLE);

                    tv_qr_tos.setText("二维码已失效,请点击图片刷新");
                    tv_qr_tos.setVisibility(View.VISIBLE);
                    refresh_img.setVisibility(View.VISIBLE);
                    refresh_img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            refresh_img.setVisibility(View.GONE);
                            shadow_img.setVisibility(View.GONE);
                            tv_qr_tos.setVisibility(View.GONE);
                            getStatus = false;
                            getQrPayUrl();
                        }
                    });
                    shadow_img.setVisibility(View.VISIBLE);
                }
            }
        };
        handler.postDelayed(runnable, time);
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    /**
     * RxBus消息接收
     *
     * @author bin
     * @time 2017/2/27
     */
    void registerRxbusEvent() {
        /**
         * 关闭activity
         */
        RxBus.with(this).setEvent(Events.PAY_COMPETE_TO_CLOSE).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (Events.PAY_COMPETE_TO_CLOSE.equals(events.getContent())) {
                    finish();
                }
            }
        }).create();
        /**
         * 新支付状态通知
         */
        RxBus.with(this).setEvent(Events.EVENT_QRCODE_PAY).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                //支付中...
                if (events.getContent() != null) {
                    ll_pay_ing.setVisibility(View.VISIBLE);
                    fl_qr.setVisibility(View.GONE);
//                    if (handler != null) {
//                        handler.removeCallbacks(runnable);
//                    }
                    Response_Pay response_pay = new Gson().fromJson(events.getContent().toString(), Response_Pay.class);
                    if ("2".equals(response_pay.getPayType())) {
                        //支付宝
                        iv_pay_type.setImageResource(R.mipmap.alipay_icon);
                        tv_pay_type_desc.setText("支付宝用户");
                    } else if ("5".equals(response_pay.getPayType())) {
                        //微信
                        iv_pay_type.setImageResource(R.mipmap.wechat_pay);
                        tv_pay_type_desc.setText("微信用户");
                    } else {
                        //云闪付
                        iv_pay_type.setImageResource(R.mipmap.yunshanfu_pay);
                        tv_pay_type_desc.setText("云闪付用户");
                    }
                    request_pay.setPayType(response_pay.getPayType());
                    if ("3".equals(response_pay.getPayStatus()) || "6".equals(response_pay.getPayStatus())) {
                        //支付失败或取消支付
                        getStatus = true;
//                        iScanpayView.dismissCountDownLoading();
                        unsubscribePeriod();
                        unsubscribeStatus();
                        Intent intent = new Intent(context, PayFailureActivity.class);
                        Bundle bundle = new Bundle();
                        request_pay.setCode("");
                        request_pay.setPayResultMessage(response_pay.getPayStatusDesc());
                        bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
                        // bundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean()); // 传递支付监控数据
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                        finish();
                    } else {
                        tv_pay_status_desc.setText(response_pay.getPayStatusDesc() + "...");
                        tv_pay_status_desc.setTag(response_pay.getPayStatus());
                        tv_qr_title.setText("收款金额");
                        ll_bottom_image.setVisibility(View.GONE);
                        tv_desc_paytype.setVisibility(View.GONE);
                        right_nav.setVisibility(View.GONE);
                    }

                }
            }
        }).create();
    }

    void initView() {
//        RelativeLayout header_header = (RelativeLayout) findViewById(R.id.header_header);
//        header_header.setBackgroundColor(Color.parseColor("#FF211A"));
        back_nav = findViewById(R.id.back_nav);
        back_nav.setOnClickListener(this);
//        back_nav.setImageResource(R.mipmap.returnwhitea);
        title_nav = findViewById(R.id.title_nav);
        title_nav.setText("二维码收款");
//        title_nav.setTextColor(Color.parseColor("#ffffff"));
        right_nav = findViewById(R.id.right_nav);
        right_nav.setText("扫码收款");
//        right_nav.setTextColor(Color.parseColor("#ffffff"));
        right_nav.setVisibility(View.VISIBLE);
        right_nav.setOnClickListener(this);
        right_nav.setVisibility(View.GONE);
        tv_qr_title = findViewById(R.id.tv_qr_title);
        tv_qr_money = findViewById(R.id.tv_qr_money);
        tv_qr_money.setText("￥" + request_pay.getTotalAmount());
        iv_qr = findViewById(R.id.iv_qr);
        iv_ali = findViewById(R.id.iv_ali);
        iv_wechat = findViewById(R.id.iv_wechat);
        iv_yunshanfu = findViewById(R.id.iv_yunshanfu);
        ll_pay_ing = findViewById(R.id.ll_pay_ing);
        iv_pay_type = findViewById(R.id.iv_pay_type);
        tv_pay_type_desc = findViewById(R.id.tv_pay_type_desc);
        tv_pay_status_desc = findViewById(R.id.tv_pay_status_desc);
        tv_desc_paytype = findViewById(R.id.tv_desc_paytype);
        shadow_img = findViewById(R.id.shadow_img);
        refresh_img = findViewById(R.id.refresh_img);
        tv_qr_tos = findViewById(R.id.tv_qr_tos);
        fl_qr = findViewById(R.id.fl_qr);
        ll_bottom_image = findViewById(R.id.ll_bottom_image);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back_nav) {
            if (ll_pay_ing.getVisibility() == View.VISIBLE && "1".equals(tv_pay_status_desc.getTag().toString())) {
                finishDialog("", "顾客正在付款中，确定返回吗？", "取消", "确定");
            } else {
                finish();
            }
        }
        if (v.getId() == R.id.right_nav) {
            Intent intent = new Intent(context, ScanpayActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
        }

    }

    private void finishDialog(String title, String msg, String btnLeftValue, String btnRightValue) {
        final PublicDialog publicDialog = new PublicDialog(this);
//        publicDialog.setIcon();
        publicDialog.setTitle(title);
        publicDialog.setMessage(msg);
        publicDialog.setLeftBtn(btnLeftValue, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publicDialog.dismiss();
            }
        });
        publicDialog.setRightBtn(btnRightValue, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                publicDialog.dismiss();
                finish();
            }
        });
        publicDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (ll_pay_ing.getVisibility() == View.VISIBLE && tv_pay_status_desc.getText().toString().contains("支付中")) {
                finishDialog("", "顾客正在付款中，确定返回吗？", "取消", "确定");
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        unsubscribeStatus();
        unsubscribePeriod();
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();

    }


}